import express from 'express';
import fetch from 'node-fetch'
import {
    checkLogin,
    checkUserRole,
} from './middleWare/index.js'
import {AIAuthorization} from '../localConfig/config.js'

import  tableModule from '../models/index.js';

const {aiConversionModel} = tableModule

const router = express.Router()

router.use(checkLogin)

//发送消息
router.post('/sendMessage', async (req,res)=>{
    console.log('checkLogin 预检中34',req.method)

    const {content,sessionId = ''} = req.body
    const {userId} = req
    if(!content){
        return res.status(500).json({
            code:500,
            data:'传参缺失',
            data:null
        })
    }

    let params = {
        "inputs": {
            "token":req.get("Token")
        },
        "query": content,
        "response_mode": "streaming",
        "conversation_id": sessionId,
        "user": userId
    }
   
    let apiUrl = 'https://api.dify.ai/v1/chat-messages'

    try{
        const longRangeRes = await fetch(apiUrl,{
            method:"POST",
            body:JSON.stringify(params),
            headers:{
                "Content-Type":"application/json;charset=utf-8",
                "Authorization":`Bearer ${AIAuthorization}`
            }
        })

        if (!longRangeRes.ok) {
            const error = await longRangeRes.text();
            console.error('Dify API 错误:', error);
            return res.status(500).json({ error: 'Dify API 请求失败' });
        }

        // 设置流式响应头
        res.setHeader('Content-Type', 'text/event-stream');
        res.setHeader('Cache-Control', 'no-cache');
        res.setHeader('Connection', 'keep-alive');
        res.setHeader('X-Content-Type-Options', 'nosniff');
        res.flushHeaders();

        
        // 将 Dify 的流式响应直接转发给客户端
        longRangeRes.body.pipe(res);

         // 错误处理
        longRangeRes.body.on('error', (err) => {
        console.error('流错误:', err);
        if (!res.headersSent) {
            res.status(500).end();
        }
        });

        // 连接关闭处理
        req.on('close', () => {
        console.log('客户端关闭连接');
        longRangeRes.body.destroy();
        });

        //连接超时
    }catch(err){
        console.log('请求出错',err)
        return res.status(500).json({
            code: 500,
            message: 'dify请求超时',
            data: { error: err.reason }
        })
    }
    
})


//保存消息
router.post("/saveMessage", checkUserRole, async (req, res) => {
   const { question,answer,sessionId,roleCode } = req.body
   const {userId}  = req
   if(question && answer && sessionId && roleCode){

    let addRes = await aiConversionModel.addConversation({
        userId: userId,
        roleCode: roleCode,
        sessionId: sessionId,
        sessionContent: {
            question: question,
            answer: answer
        }
    })
    if(addRes){
        return res.json({
            code:200,
            message:'保存成功',
            data:true
        })
    }else{
        return res.status(500).json({
            code:500,
            message:'保存失败',
            data:false
        })
    }
       
   }else{
    return res.status(500).json({
            code:500,
            message:'传参缺失',
            data:null
        })
   }

})


// 查询消息接口
router.post("/searchConversitionList",checkUserRole,async (req,res)=>{
    const {roleCode} = req.body
    const {userId} = req
    if(roleCode){
        let result  = await aiConversionModel.getConversationByUserAndRole({userId, roleCode})
        return res.json({
            code:200,
            message:'查询成功',
            data:result
        })
    }else{
        return res.status(500).json({
            code:500,
            message:'传参缺失',
            data:null
        })
    }
})


// 清空历史消息接口
router.post('/deleteHistoryConversition',checkUserRole,async (req,res)=>{
    const {roleCode} = req.body
    const {userId} = req

    if(roleCode){
        let delRes = await aiConversionModel.deleteConversationByUserAndRole({userId, roleCode})
        if(delRes){
             return res.json({
                code:200,
                message:'删除成功',
                data:true
            })
        }else{
            return res.json({
                code:200,
                message:'没有数据可删除',
                data:true
            })
        }
    }else{
        return res.status(500).json({
            code:500,
            message:'传参缺失',
            data:null
        })
    }
})



export default router